package com.config;

import com.annotation.Values;
import com.pojo.LoginUser;
import lombok.Data;
import lombok.Getter;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;

@Data
public class DBConfig {
    @Getter
    private static DBConfig instance = new DBConfig();

    @Values(value = "datasource.driverClass")
    private String driverClass;
    @Values(value = "datasource.jdbcUrl")
    private String jdbcUrl;
    @Values(value = "datasource.username")
    private String username;
    @Values(value = "datasource.password")
    private String password;

    private DBConfig(){
        Field[] declaredFields = DBConfig.class.getDeclaredFields();
        Properties properties = LoadProperties();
        Arrays.stream(declaredFields).filter(field ->field.isAnnotationPresent(Values.class)).forEach(f->{
            String property = properties.getProperty(f.getAnnotation(Values.class).value());
            try {
                f.set(this,property);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
    }

    private static Properties LoadProperties(){
        Properties properties = new Properties();
        try(InputStream resourceAsStream = LoginUser.class.getClassLoader().getResourceAsStream("application.properties")) {
            properties.load(resourceAsStream);
            return properties;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
